package org.finesys.common.quartz.config;

import org.quartz.JobKey;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.lang.NonNull;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

/**
 * 使得Quartz作业可以利用Spring的依赖注入和AOP特性‌
 */
public class AutowireCapableBeanJobFactory extends SpringBeanJobFactory {

    private final AutowireCapableBeanFactory beanFactory;

    public AutowireCapableBeanJobFactory(AutowireCapableBeanFactory autowireCapableBeanFactory) {
        this.beanFactory = autowireCapableBeanFactory;
    }

    @Override
    @NonNull
    protected Object createJobInstance(@NonNull TriggerFiredBundle bundle) throws Exception {
        Object jobInstance = super.createJobInstance(bundle);
        beanFactory.autowireBean(jobInstance);
        //注入beanName
        JobKey jobKey = bundle.getTrigger().getJobKey();
        String beanName = jobKey + jobKey.getName();
        beanFactory.initializeBean(jobInstance, beanName);
        return jobInstance;
    }
}
